//
//  TTTeJiaView.m
//  TaoTuo
//
//  Created by LG on 2020/8/28.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTTeJiaView.h"
#import "TTRecyclingHomeViewCell.h"
#import "TTRecyclingHomeListModel.h"
#import "TTRecyclingDetailViewController.h"
#import "LLDateUtilis.h"

static NSString *cellID = @"cell";

@interface TTTeJiaView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) YYTimer *timer;
@property (nonatomic, copy)  NSString *cellBtnTitle;

@end

@implementation TTTeJiaView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.page = 1;
        @weakify(self)
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            self.page++;
            [self requestListDatas];
        }];
        
        [self requestListDatas];
        
    }
    return self;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTRecyclingHomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTRecyclingHomeListModel *model = self.dataArray[indexPath.row];
    TTRecyclingDetailViewController *detailVC = [[TTRecyclingDetailViewController alloc] initWithGoodsID:model.InformationGoodsId];
    [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
}


// 必须加（用于联动）
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.scrollCallback(scrollView);
}

#pragma mark - JXPagingViewListViewDelegate
- (UIView *)listView {
    return self;
}
/**
返回一个可滚动的视图
*/
- (UIScrollView *)listScrollView {
    return self.tableView;
}
/**
用于联动
*/
- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}


- (void)timerAction
{
    if (self.dataArray.count == 0) {
        return;
    }
    for (TTRecyclingHomeListModel *model in self.dataArray) {
        
        model.totalSecond--;
        if (model.totalSecond < 0) {
            model.totalSecond = 0;
        }
        model.hour = model.totalSecond / 3600;
        model.minute = model.totalSecond % 3600 / 60;
        model.second = model.totalSecond % 3600 % 60;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"recyclingHomeCellTimerNotify_key" object:nil];
}


/// 回收列表
- (void)requestListDatas
{
    NSDictionary *dic = @{
        @"param.goodsType" : @2,
        @"param.pageIndex" : @(self.page),
        @"param.pageSize" : @20,
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:recycling_home_list_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self)
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        if (self.timer == nil) {
            self.timer = [YYTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) repeats:YES];
        }
        for (NSDictionary *dic in responseObject) {
            TTRecyclingHomeListModel *model = [TTRecyclingHomeListModel modelWithJSON:dic];
            [self.dataArray addObject:model];
            if (model.SalesModel == 2) {
                // 获取当前时间
                NSString *currentDateStr = [LLDateUtilis getCurrentTimeString];
                // 距离开始时间差
                NSDateComponents *diff = [LLDateUtilis compareFromDateString:model.StartTime toDateString:currentDateStr deteUnit:Hour | Minute | Second];
                if (diff.second < 0) {
                    // 还未开始
                    diff = [LLDateUtilis compareFromDateString:currentDateStr toDateString:model.StartTime deteUnit:Hour | Minute | Second];
                    self.cellBtnTitle = @"距离开始";
                    
                } else {
                    // 时间差
                    diff = [LLDateUtilis compareFromDateString:currentDateStr toDateString:model.EndTime deteUnit:Hour | Minute | Second];
                    if (diff.second < 0) {
                        self.cellBtnTitle = @"已结束";
                    } else {
                        self.cellBtnTitle = @"距离结束";
                    }
                }
                
                model.hour = diff.hour >= 0 ? diff.hour : 0;
                model.minute = diff.minute >= 0 ? diff.minute : 0;
                model.second = diff.second >= 0 ? diff.second : 0;
                // 总秒数
                model.totalSecond = model.hour * 3600 + model.minute * 60 + model.second;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"recyclingHomeCellTimerNotify_key" object:nil];
                
            }
        }
        
        if ([responseObject count] < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.tableView];
}

- (void)refreshDatas
{
    self.page = 1;
    [self requestListDatas];
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 150;
        _tableView.emptyImageName = @"回收无数据页面";
        _tableView.emptyTitel = @"暂无相关商品";
        _tableView.verticalOffset = -100;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTRecyclingHomeViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [self addSubview:_tableView];
        
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}

@end
